package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.RateRisesCouponsDao;
import com.edais.dao.WxCouponActivityDao;
import com.edais.domain.RateRisesCoupons;
import com.edais.domain.WxCouponActivity;
import com.edais.service.WxCouponActivityService;
import com.edais.util.Consts;

@Service

@Transactional
public class WxCouponActivityServiceImpl implements WxCouponActivityService {
	
	private static final Log logger = LogFactory.getLog(WxCouponActivityServiceImpl.class);
	
	@Autowired
	private WxCouponActivityDao wxCouponActivityDao;
	
	@Autowired
	private RateRisesCouponsDao rateRisesCouponsDao;
	
	private WxCouponActivity wxCouponActivity;
	
	/**
	 * 获取活动期加息券总数
	 * @return 
	 * */
	@Override
	public Map<String, Object> queryWxCouponInfoByActivity() throws Exception {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		wxCouponActivity=wxCouponActivityDao.queryWxCouponActivityInfo();
		//活动日期验证
		Date date=new Date();
		java.text.SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");
		Date startDate=fmt.parse(wxCouponActivity.getBeginDate());
		Date endDate=fmt.parse(wxCouponActivity.getEndDate());
		String flag="0";//0默认为活动期内
		
		Calendar cal = Calendar.getInstance();
		cal.setTime(fmt.parse(fmt.format(endDate)));
		cal.add(Calendar.DATE, 1);
		if(date.getTime()<startDate.getTime()||date.getTime()>=cal.getTime().getTime()){
			flag="1";//不在活动期
		}
		resultMap.put("isActivityDate", flag);
		resultMap.put("totalNum", wxCouponActivity.getTotalAmount());
		resultMap.put("beginDate", wxCouponActivity.getBeginDate());
		resultMap.put("endDate", wxCouponActivity.getEndDate());
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "查询成功");
		return resultMap;
	}
	
	/**
	 * 获取加息券（疯抢活动）
	 * @param params
	 * @return 
	 * */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> gainWxCouponForUser(Integer userId) throws Exception {
		//获取加息券验证
		String checkResult=verifyProcessRight(userId);
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(!"SUCCESS".equals(checkResult)){
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("resmsg_cn", checkResult);
			return resultMap;
		}
		
		RateRisesCoupons coupons = new RateRisesCoupons();
		//计算有效期
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		cal.setTime(sdf.parse(sdf.format(new Date())));
		cal.add(Calendar.DATE, Integer.parseInt(wxCouponActivity.getValidDays())-1);
		Date validityDate = cal.getTime();
		//设置加息券信息:108-定期，109-活期
		coupons.setUser_id(Long.valueOf(userId));
		coupons.setValidity_period(validityDate);
		coupons.setProduct_id(wxCouponActivity.getProductType());
		int days=Integer.parseInt(wxCouponActivity.getRisesDays());
		days=wxCouponActivity.getProductType().equals("108")?days/30:days;
		coupons.setRate_rises_days(days);
		coupons.setRate_rises(new BigDecimal(wxCouponActivity.getRateRises().trim()));
		coupons.setStatus("0");
		coupons.setGet_way("12");
		coupons.setCreate_time(new Date());
		coupons.setUse_flag("1");
		//添加加息券
		this.rateRisesCouponsDao.insertRateRisesCoupons(coupons);
		//更显库存信息
		Integer i=wxCouponActivityDao.modifyAmtAfterGain();
		if(1!=i){
			logger.info("库存更新失败，当前库存量为："+wxCouponActivity.getTotalAmount());
			throw new RuntimeException("获取加息券失败");
		}
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", checkResult);
		resultMap.put("rateRises",wxCouponActivity.getRateRises());
		resultMap.put("risesDays", wxCouponActivity.getRisesDays());
		resultMap.put("productType", wxCouponActivity.getProductType());
		return resultMap;
	}
	
	/**
	 *	获取权限及流程验证
	 * @param params
	 * @return 
	 * */
	private String verifyProcessRight(Integer userId) throws Exception{
		String result="";
		//库存验证
		wxCouponActivity=wxCouponActivityDao.queryWxCouponActivityInfo();
		if(null==wxCouponActivity.getTotalAmount()||0==wxCouponActivity.getTotalAmount()){
			result="加息券已领完，请等待下次活动开启！";
			return result;
		}
		//活动日期验证
		java.text.SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");
		Date date=new Date();
		Date startDate=fmt.parse(wxCouponActivity.getBeginDate());
		Date endDate=fmt.parse(wxCouponActivity.getEndDate());
		Calendar cal = Calendar.getInstance();
		cal.setTime(fmt.parse(fmt.format(endDate)));
		cal.add(Calendar.DATE, 1);
		if(date.getTime()<startDate.getTime()||date.getTime()>=cal.getTime().getTime()){
			result="暂时不可领取加息券！";
			return result;
		}
		//用户是否已经领取过
		String str=wxCouponActivityDao.queryGainedFlag(userId);
		if(StringUtils.isNotEmpty(str)){
			result="您已经领取过加息券咯！";
			return result;
		}
		result="SUCCESS";
		return result;
	}
	
}
